package controller;

/*
 * Action for administrator menu (register users etc)
 */

import java.util.ArrayList;
import java.util.List;

import helper.UserType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import databeans.User;

import model.Model;
import model.UserDAO;

public class AdminAction extends Action {
	private UserDAO userDAO;
	
	public AdminAction(Model model) {
		userDAO = model.getUserDAO();
	}
    
	public String getName() {
		return "admin.do";
	}
    
    public String perform(HttpServletRequest request) {
    	User[] user_list;
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);

        // Check if user is admin
    	HttpSession session = request.getSession(false);
    	User user = (User) session.getAttribute("user");
    	
    	if (user.getType() != UserType.ADMIN) {
    		errors.add("You are not an admin!");
    		return "homepage.jsp";
    	}
    	
    	String button = request.getParameter("button");
    	
    	if (button == null)
    		return "admin.jsp";
    	
    	if (button.equals("Register User"))
    		return "register.jsp";
    	if (button.equals("Delete User")){ 
    		try {
				user_list = userDAO.getUsers();
				synchronized(session) {
	    			session.setAttribute("userlist", user_list);
	    		}
	    		return "deleteuser.jsp";
			} catch (DAOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    	if (button.equals("Change User's Password")){ 
    		try {
				User change_user = userDAO.lookup(user.getUserid());
				synchronized(session) {
	    			session.setAttribute("userchange", change_user);
	    			session.setAttribute("redirectto", "admin.jsp");
	    		}
	    		return "changepassword.jsp";
			} catch (DAOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    	if (button.equals("Change User's Password"))
    		return "changepw.jsp";
    	if (button.equals("Logout")) {
    		synchronized(session) {
    			session.setAttribute("user", null);
    		}
			return "homepage.jsp";
    	}
    	errors.add("Illegal button value of " + button);
    	return "errors.jsp";
    }
}
